<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, updateUserStatus, deleteUser, type UserInfo } from '../../api/user'
import type { UserPageRequest } from '../../api/user'

const emit = defineEmits(['create-user', 'edit-user'])

// 用户列表相关
const userList = ref<UserInfo[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 角色选项
const roleOptions = [
  { value: 1, label: '超级管理员' },
  { value: 2, label: '管理员' },
  { value: 3, label: '普通用户' }
]

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params: UserPageRequest = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: keyword.value
    }
    const res = await getUserList(params)
    
    // 确保用户列表数据正确处理
    if (res.data && res.data.items) {
      // 打印检查返回的第一个用户数据结构
      if (res.data.items.length > 0) {
        console.log('用户数据示例:', res.data.items[0])
      }
      
      // 直接使用原始数据
      userList.value = res.data.items
      total.value = res.data.total
    } else {
      userList.value = []
      total.value = 0
    }
  } catch (error) {
    // 错误已被拦截器处理
    console.error('获取用户列表失败:', error)
    userList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索并刷新用户列表
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchUserList()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchUserList()
}

// 用户状态处理
const handleStatusChange = async (row: UserInfo) => {
  // 获取正确的用户ID（兼容大写ID或小写id）
  const userId = row.ID || row.id;
  
  if (!userId) {
    ElMessage.error('无效的用户ID，无法更新状态');
    return;
  }
  
  // 保存原始状态值，以便在失败时还原
  const originalStatus = row.status
  // 更新状态值（切换）
  row.status = row.status === 1 ? 0 : 1
  
  try {
    await updateUserStatus(userId, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 失败时还原状态
    row.status = originalStatus
    ElMessage.error('更新状态失败')
  }
}

// 删除用户
const handleDelete = (row: UserInfo) => {
  // 调试：打印用户ID及其类型
  console.log('删除用户ID:', row.ID, '类型:', typeof row.ID, 'row对象:', row);
  
  // 获取正确的用户ID（兼容大写ID或小写id）
  const userId = row.ID || row.id;
  
  // 验证用户ID是否有效
  if (!userId || isNaN(Number(userId)) || Number(userId) <= 0) {
    ElMessage.error('无效的用户ID，无法删除');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除用户 ${row.nickname || row.username} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(userId)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      // 显示具体错误信息
      if (error instanceof Error) {
        ElMessage.error(error.message);
      } else {
        ElMessage.error('删除用户失败');
      }
    }
  })
}

// 创建用户对话框
const handleCreateUser = () => {
  emit('create-user')
}

// 编辑用户
const handleEdit = (row: UserInfo) => {
  emit('edit-user', row)
}

// 初始化
onMounted(() => {
  fetchUserList()
})

// 暴露方法给父组件
defineExpose({
  fetchUserList
})
</script>

<template>
  <div class="user-list-component">
    <div class="action-bar">
      <div class="search-wrapper">
        <div class="search-input">
          <i class="search-icon el-icon-search"></i>
          <input 
            type="text" 
            v-model="keyword" 
            placeholder="搜索用户名或昵称" 
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">搜索</button>
        </div>
      </div>
      
      <div class="action-buttons">
        <button class="btn-primary" @click="handleCreateUser">
          <i class="btn-icon el-icon-plus"></i>
          <span>创建用户</span>
        </button>
      </div>
    </div>
    
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        :header-cell-style="{
          background: '#f9fafc',
          color: '#606266',
          fontWeight: '600',
          borderBottom: '2px solid #EBEEF5'
        }"
        :cell-style="{
          padding: '12px 0'
        }"
      >
        <el-table-column prop="ID" label="ID" width="80" align="center">
          <template #default="scope">
            <span class="user-id">{{ scope.row.ID || scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="role" label="角色" min-width="140">
          <template #default="{ row }">
            <span class="role-text" :class="'role-' + row.role">
              {{ roleOptions.find(r => r.value === row.role)?.label }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <span 
              class="status-badge" 
              :class="row.status === 1 ? 'status-active' : 'status-inactive'"
            >
              {{ row.status === 1 ? '已启用' : '已禁用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录时间" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <button 
                class="action-btn btn-primary"
                @click="handleEdit(row)"
              >
                编辑
              </button>
              <button 
                class="action-btn" 
                :class="row.status === 1 ? 'btn-warning' : 'btn-success'"
                @click="handleStatusChange(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </button>
              <button 
                class="action-btn btn-danger"
                @click="handleDelete(row)"
              >
                删除
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="table-footer">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@use "sass:color";

.user-list-component {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  
  .search-wrapper {
    flex: 1;
    max-width: 500px;
    
    .search-input {
      position: relative;
      width: 100%;
      
      .search-icon {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-light);
        font-size: 16px;
      }
      
      input {
        width: 100%;
        border: 1px solid var(--border-color);
        border-radius: 50px;
        padding: 12px 15px 12px 40px;
        font-size: 14px;
        color: var(--text-primary);
        outline: none;
        transition: var(--transition);
        
        &:focus {
          border-color: var(--primary-color);
          box-shadow: 0 0 0 2px rgba(58, 124, 254, 0.2);
        }
      }
      
      .search-btn {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        background-color: var(--primary-color);
        color: white;
        border: none;
        border-radius: 50px;
        padding: 8px 20px;
        font-size: 14px;
        cursor: pointer;
        transition: var(--transition);
        
        &:hover {
          background-color: color.adjust(#3a7cfe, $lightness: -10%);
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
    
    .btn-primary {
      background-color: var(--primary-color);
      color: white;
      border: none;
      border-radius: var(--radius-sm);
      padding: 10px 20px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 5px;
      transition: var(--transition);
      
      &:hover {
        background-color: color.adjust(#3a7cfe, $lightness: -10%);
        transform: translateY(-2px);
        box-shadow: var(--shadow-sm);
      }
    }
  }
}

.table-card {
  background-color: var(--card-bg);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-sm);
  padding: 20px;
  
  .user-id {
    font-weight: 600;
    background-color: var(--primary-light);
    color: var(--primary-color);
    padding: 4px 8px;
    border-radius: var(--radius-sm);
    display: inline-block;
    min-width: 36px;
    text-align: center;
  }
  
  .status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 50px;
    font-size: 12px;
    font-weight: 500;
    
    &.status-active {
      background-color: rgba(66, 185, 131, 0.1);
      color: var(--success-color);
    }
    
    &.status-inactive {
      background-color: rgba(245, 108, 108, 0.1);
      color: var(--danger-color);
    }
  }

  /* 角色样式 */
  .role-text {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 500;
    
    &.role-1 {
      background-color: #ffd700;
      color: #b8860b;
    }
    
    &.role-2 {
      background-color: #e6f7ff;
      color: #1890ff;
    }
    
    &.role-3 {
      background-color: #f6ffed;
      color: #52c41a;
    }
  }
  
  .table-actions {
    display: flex;
    gap: 8px;
    
    .action-btn {
      border: none;
      border-radius: var(--radius-sm);
      padding: 6px 12px;
      font-size: 12px;
      cursor: pointer;
      transition: var(--transition);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-sm);
      }
      
      &.btn-primary {
        background-color: rgba(58, 124, 254, 0.1);
        color: var(--primary-color);
        
        &:hover {
          background-color: var(--primary-color);
          color: white;
        }
      }
      
      &.btn-success {
        background-color: rgba(66, 185, 131, 0.1);
        color: var(--success-color);
        
        &:hover {
          background-color: var(--success-color);
          color: white;
        }
      }
      
      &.btn-warning {
        background-color: rgba(230, 162, 60, 0.1);
        color: var(--warning-color);
        
        &:hover {
          background-color: var(--warning-color);
          color: white;
        }
      }
      
      &.btn-danger {
        background-color: rgba(245, 108, 108, 0.1);
        color: var(--danger-color);
        
        &:hover {
          background-color: var(--danger-color);
          color: white;
        }
      }
    }
  }
  
  .table-footer {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 